package com.suns.client;

import com.suns.HelloServiceGrpc;
import com.suns.HelloServiceGrpc.HelloServiceStub;
import com.suns.SimpleRequest;
import com.suns.SimpleResponse;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import java.util.concurrent.TimeUnit;

/**
 * @author xiangminwen
 * @date 2024/4/3 11:13
 */
public class GrpcClient3 {

    public static void main(String[] args) throws Exception {
        //创建通信管道
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9000).usePlaintext().build();
        try {
            //获得代理对象Stub，使用异步监听方式处理
            HelloServiceStub serviceStub = HelloServiceGrpc.newStub(channel);
            //监听服务端请求返回
            StreamObserver<SimpleRequest> req = serviceStub.hello3(new StreamObserver<SimpleResponse>() {
                @Override
                public void onNext(SimpleResponse value) {
                    System.out.println(value.getData());
                }

                @Override
                public void onError(Throwable t) {

                }

                @Override
                public void onCompleted() {
                    //接收服务端所有响应完成的通知
                }
            });
            //发送请求数据
            for (int i = 0; i < 3; i++) {
                req.onNext(SimpleRequest.newBuilder().setName("client" + i).setAge(10).addCode("code1").addCode("code2").build());
                TimeUnit.SECONDS.sleep(1);
            }
            req.onCompleted();
            channel.awaitTermination(6, TimeUnit.SECONDS);
        } finally {
            if (!channel.isShutdown()) {
                channel.shutdown().awaitTermination(2, TimeUnit.SECONDS);
            }
        }
    }
}
